import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/product.dart';
import '../services/api_service.dart';

class FavoritesProvider extends ChangeNotifier {
  static const _key = 'favorites_ids';
  final ApiService _api = ApiService();
  final Set<int> _ids = <int>{};
  final Map<int, Product> _cache = <int, Product>{};

  Set<int> get ids => _ids;
  List<Product> get items => _ids.map((id) => _cache[id]).whereType<Product>().toList();

  FavoritesProvider() {
    _load();
  }

  Future<void> _load() async {
    final prefs = await SharedPreferences.getInstance();
    final raw = prefs.getString(_key);
    if (raw != null) {
      final list = (jsonDecode(raw) as List).map((e) => e as int).toList();
      _ids.addAll(list);
      notifyListeners();
    }
  }

  Future<void> _persist() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_key, jsonEncode(_ids.toList()));
  }

  Future<void> toggle(Product p) async {
    if (_ids.contains(p.id)) {
      _ids.remove(p.id);
      _cache.remove(p.id);
    } else {
      _ids.add(p.id);
      _cache[p.id] = p;
    }
    await _persist();
    notifyListeners();
  }

  bool isFav(int id) => _ids.contains(id);

  Future<Product?> ensureItem(int id) async {
    if (_cache.containsKey(id)) return _cache[id];
    try {
      final p = await _api.getProductById(id);
      _cache[id] = p;
      notifyListeners();
      return p;
    } catch (_) {
      return null;
    }
  }

  Future<void> remove(int id) async {
    _ids.remove(id);
    _cache.remove(id);
    await _persist();
    notifyListeners();
  }
}